import React, { useState } from "react";

import styles from "./style.module.scss";

import { ReactComponent as IconAdd } from "assets/icons/TODO_ADD.svg";
import { Button } from "antd-mobile";

interface Props {
  addTodoToList: (content: string) => void;
}

export const AddPanel = ({ addTodoToList }: Props) => {
  const [value, setValue] = useState("");

  // 禁掉input框的空格键
  const disableSpaceBar = (event: React.KeyboardEvent<HTMLInputElement>) => {
    // console.log(event.target.value);
    if (event.code === "Space") {
      event.target.value = event.target.value.replace(/\s+/g, "");
      return false;
    }
  };

  const handleAddTodo = () => {
    const newAddContent = value.trim();
    if(newAddContent) {
      addTodoToList(newAddContent);
    }
    setValue("");
  };

  const handleEnter = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.code === "Enter") {
      handleAddTodo();
    }
  };

  return (
    <div className={styles.wrap}>
      <div className={styles.addPanel}>
        <IconAdd onClick={() => handleAddTodo()} />
        <input
          type="text"
          className={styles.input}
          onKeyPress={(event) => disableSpaceBar(event)}
          onKeyUp={(event) => handleEnter(event)}
          placeholder="添加任务"
          value={value}
          onChange={(event) => {
            setValue(event.target.value);
          }}
        />
      </div>
      <Button color="primary" size="small" style={{
        "--background-color": "#eeeff3",
        "--text-color": "#333"
      }} onClick={() => handleAddTodo()}>
        保存
      </Button>
    </div>
  );
};
